import { observable, action, configure, flow } from 'mobx';
import _ from 'lodash';
import pinyin from 'pinyin';
import { del } from '../../../utils/request';
import { getCustomers } from '../services';

configure({ enforceActions: true });

const machining = (data = []) => {
  if (data.length < 1) {
    return data;
  }
  const _data = _.sortBy(
    _.map(data, d => {
      d.index = _.upperCase(
        pinyin(d.name, { style: pinyin.STYLE_NORMAL }).join('')
      );
      d.start = d.index.charAt(0);
      return d;
    }),
    'index'
  );
  const lastData = [];
  const firstSection = _.remove(_data, ({ start }) => /\W|\d/i.test(start));
  if (!_.isEmpty(firstSection)) {
    lastData.push({ data: firstSection, title: '#' });
  }
  _.forEach(_.groupBy(_data, ({ start }) => start), (v, k) => {
    lastData.push({ data: v, title: k });
  });
  return lastData;
};

class Customers {
  @observable data = [];
  @observable searchResult = [];
  @observable searchPending = false;
  @observable pending = false;
  @observable needReload = false;
  @action
  init = force => {
    this.gets(force);
  };
  @action
  reset = () => {
    this.data = [];
    this.searchResult = [];
    this.searchPending = false;
    this.pending = false;
    this.needReload = false;
  }
  gets = flow(function*(force) {
    if (this.data.length > 0 && !force && !this.needReload) {
      const _data = yield storage.getAllDataForKey('customers');
      return;
    }
    if (force) {
      this.fetch();
      return;
    }
    try {
      const data = yield storage.getAllDataForKey('customers');
      if (data.length < 1) {
        this.fetch();
        return;
      }
      this.data = machining(data);
      this.needReload = false;
    } catch (error) {
      this.fetch();
    }
  });
  @action
  setReloadStatus = bool => {
    this.needReload = bool;
  };
  fetch = flow(function*(empty) {
    if (empty) {
      this.data = [];
      return;
    }
    this.pending = true;
    try {
      const data = yield getCustomers();
      if (data) {
        const { customers } = data;
        _.forEach(customers, customer => {
          storage.save({
            key: 'customers',
            data: customer,
            id: customer.customerId
          });
        });
        this.data = machining([...customers]);
        this.needReload = false;
      }
    } finally {
      this.pending = false;
    }
  });
  search = flow(function*(key) {
    this.searchPending = true;
    try {
      const data = yield getCustomers({ key });
      if (data) {
        return data.customers;
      }
    } finally {
      this.searchPending = false;
    }
  });
  remove = flow(function*(id) {
    const data = yield del(`v1/customers/${id}`);
    if (data) {
      storage
        .load({
          key: 'customers',
          id
        })
        .then(() => {
          storage.remove({
            key: 'customers',
            id
          });
          return true;
        }).then(() => {
          this.setReloadStatus(true);
          return true;
        }).then(() => {
          this.init()
        });
      //this.gets(true);
    }
  });
}

export default new Customers();
